package ru.adhoc.truealarmfree.alarmreceiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import ru.adhoc.truealarmfree.R;
import ru.adhoc.truealarmfree.db.DbHelper;
import ru.adhoc.truealarmfree.player.SoundPlayer;
import ru.adhoc.truealarmfree.utils.Constants;
import ru.adhoc.truealarmfree.utils.Util;


public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

    private final String ONE_TIME = "onetime";
    private DbHelper DbHelper;


    @Override
    public void onReceive(Context context, Intent intent) {

        runAlarm(context, intent.getExtras().getInt("id"));
    }

//Установка времени срабатывания и интервала повторения
    public void SetAlarm(Context context, long alarmTime, int requestCode)
    {
        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
        intent.putExtra(ONE_TIME, Boolean.FALSE);

        intent.setAction(Integer.toString(requestCode));
        intent.putExtra("id", requestCode);

        PendingIntent pi = PendingIntent.getBroadcast(context, requestCode, intent, 0);
        am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 86400000 , pi);
    }

    public void CancelAlarm(Context context, int requestCode)
    {
        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);

        intent.setAction(Integer.toString(requestCode));
        intent.putExtra("id", requestCode);

        PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);

    }

//Инициирует срабатывание будильника
    private void runAlarm(Context context, int id){

//получаем ури по айди и запускаем нужную мелодию
        DbHelper = DbHelper.getInstance(context);
        SQLiteDatabase db = DbHelper.getWritableDatabase();
        Uri uri = Uri.parse("android.resource://ru.adhoc.truealarmfree/" + R.raw.nature);

        try {
            uri = DbHelper.getAlarmSoundURI(db, id);
        }
        finally {
           if(db != null)
               db.close();
        }

        SoundPlayer.getInstance(context).playSound(uri, id, true);
        Constants.getInstance(context).setAlarmed(true,id);

        Intent cancelAlarm = Util.getInstance(context).getActualCancelAlarmIntent();
        cancelAlarm.putExtra("id", id);
        cancelAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(cancelAlarm);
    }


}
